package org.springframework.samples.petclinic.Services;

import org.springframework.samples.petclinic.model.owner.Owner;
import org.springframework.samples.petclinic.model.owner.OwnerRepository;
import org.springframework.samples.petclinic.model.owner.Pet;
import org.springframework.samples.petclinic.model.owner.Visit;
import org.springframework.samples.petclinic.model.usrAccount.Account;
import org.springframework.samples.petclinic.model.usrAccount.AccountRepository;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Vector;

@Service
public class UserServices {
	private final AccountRepository accountRepository;
	private final OwnerRepository ownerRepository;

	public UserServices(AccountRepository accountRepository, OwnerRepository ownerRepository) {
		this.accountRepository = accountRepository;
		this.ownerRepository = ownerRepository;
	}

	public boolean verifyPasword(String accountName,String password){
		if (accountName == null) {
			return false;
		}
		if (accountRepository.findByAccountName(accountName).size()!=0){
			Account account = accountRepository.findByAccountName(accountName).get(0);
			String shouldBePassword = account.getUsrPassword();
			if (shouldBePassword.equals(password)) return true;
		}
		return false;
	}

	public boolean isExist(String accountName){
		if (accountRepository.findByAccountName(accountName)!=null) return true;
		else return false;
	}

	public void save(Owner newOwner,String password){
		ownerRepository.save(newOwner);
		accountRepository.save(new Account(newOwner.getAccountName(), password));
	}
	public Owner findByAccountName(String accountName){
		return ownerRepository.findByAccountName(accountName);
	}

	public void updateOwner(Owner editedOwner){
		ownerRepository.save(editedOwner);
	}

	public List<Visit> getVisits(Integer usrID){
		List<Visit> toBeReturn = new Vector();
		Owner owner = ownerRepository.findById(usrID);
		for (Pet pet: owner.getPets()
			 ) {
			for (Visit visit:pet.getVisits()
				 ) {
				toBeReturn.add(visit);
			}
		}
		return toBeReturn;
	}

	public void addVisit(Visit newVisit,Owner owner,Integer petID){
		owner.addVisit(petID,newVisit);
		ownerRepository.save(owner);
	}
	public boolean cancelVisit(Integer visitId,Integer petID,Owner owner){
		boolean succeeded = owner.cancelVisit(visitId,petID);
		ownerRepository.save(owner);
		return succeeded;
	}
}
